<template>
  <div>
    <n-card :bordered="false" class="mt-4 proCard">
      <div class="search">
        <n-grid :cols="1" @keydown.enter.native="handleSearch">
          <n-gi>
            <n-form
              :model="queryForm"
              ref="formRef"
              label-placement="left"
              :inline="true"
            >
              <n-form-item label="角色名称" path="roleName">
                <n-input placeholder="请输入角色名称查询" v-model:value="queryForm.roleName" />
              </n-form-item>
              <n-form-item style="display: flex; justify-content: flex-end;">
                <n-button @click="handleSearch" type="primary">
                  <template #icon>
                    <n-icon>
                      <SearchOutlined/>
                    </n-icon>
                  </template>查询</n-button>
                <!--              <n-button  @click="handleReSet" style="margin-left: 10px" type="default">重置</n-button>-->
              </n-form-item>
            </n-form>
          </n-gi>
        </n-grid>
      </div>
      <div class="operation" style="margin-bottom: 1vh">
        <n-grid :cols="14" >
          <n-button type="primary" @click="add">
            <template #icon>
              <n-icon>
                <PlusOutlined />
              </n-icon>
            </template>
            添加
          </n-button>
          <n-button type="error" style="margin-left: 5px" @click="batchDelete">
            <template #icon>
              <n-icon>
                <DeleteFilled />
              </n-icon>
            </template>
            删除
          </n-button>
        </n-grid>
      </div>
      <n-grid :cols="1" style="margin-bottom: 1vh;">
        <n-gi :span="1">
          <n-alert type="info" size="small">
            已选择
            <span class="select-count">{{selectRows.length}}</span> 项
            <a class="select-clear" @click="clearSelect" v-if="selectRows.length>0">清空</a>
          </n-alert>
        </n-gi>
      </n-grid>
      <n-data-table
        ref="table"
        :columns="actionColumn"
        :pagination="pagination"
        :loading="dataLoading"
        :data="roleData"
        :row-key="row => row.id"
        @update:checked-row-keys="handleCheck"
        :checked-row-keys="selectRows"
        @update:page-size="changePageSize"
      >
      </n-data-table>
    </n-card>
    <n-modal v-model:show="showModal" :show-icon="false" preset="dialog" :title="editRoleTitle">
      <div class="py-3 menu-list">
        <n-tree
          block-line
          :cascade="false"
          checkable
          :virtual-scroll="true"
          :data="treeData"
          :expanded-keys="expandedKeys"
          :checked-keys="checkedKeys"
          style="max-height: 500px; overflow: hidden"
          @update:checked-keys="checkedTree"
          @update:expanded-keys="expandedKeysTree"
        />
      </div>
      <template #action>
        <n-space>
          <n-button type="info" ghost icon-placement="left" @click="packHandle">
            全部{{ expandedKeys.length ? '收起' : '展开' }}
          </n-button>
          <n-button type="info" ghost icon-placement="left" @click="checkedAllHandle">
            全部{{ checkedAll ? '取消' : '选择' }}
          </n-button>
          <n-button type="primary" :loading="formBtnLoading" @click="confirmForm">提交</n-button>
        </n-space>
      </template>
    </n-modal>
    <role-form ref="roleFormRef" :drawerTitle="drawerTitle" @on-success="onSuccess"/>
  </div>
</template>

<script lang="ts" setup>
  import { reactive, ref, h, onMounted } from 'vue';
  import { useMessage,useDialog } from 'naive-ui';
  import { getRoleList,saveRolePermission,deleteRole } from '@/api/system/role';
  import {getMenuList, removeMenu} from '@/api/system/menu';
  import RoleForm from './RoleForm.vue'
  import { PlusOutlined,SearchOutlined,DeleteFilled } from '@vicons/antd';
  import { NTag,NButton } from 'naive-ui';
  import { getTreeAll } from '@/utils';
  import { useRouter } from 'vue-router';
  const router = useRouter();
  const formRef: any = ref(null);
  const message = useMessage();
  const dialog  = useDialog();
  const actionRef = ref();
  const roleData=ref([])
  const showModal = ref(false);
  const formBtnLoading = ref(false);
  const checkedAll = ref(false);
  const editRoleTitle = ref('');
  const treeData = ref([]);
  const expandedKeys = ref([]);
  const dataLoading=ref(false);
  const drawerTitle=ref(null);
  const roleFormRef=ref(null);
  const selectRows=ref([])
  const queryForm=reactive({
    roleName:'',
    page:1,
    pageSize:10
  })
  const roleId=ref('')
  const checkedKeys:any = ref([]);
  const pagination=ref({
    itemCount:0,
    prefix ({ itemCount }) {
      return `共 ${itemCount} 项`
    },
    page: 1,
    pageSize: 10,
    showSizePicker: true,
    pageSizes: [10, 20, 30,40,50],
  })
  const actionColumn = reactive([
    {
      type: "selection",
      width: 60,
      align: "center",
      fixed: "left"
    },
    {
      type: "index",
      width: 60,
      align: "center",
      fixed: "left"
    },
    {
      title: '角色名称',
      key: 'roleName',
      align: "center",
    },
    {
      title: '角色编码',
      key: 'roleCode',
      align: "center",
    },
    {
      title: "创建时间",
      key: "createTime",
      align: "center",
    },
    {
      title: '是否默认角色',
      key: 'isDefault',
      render(row) {
        return h(
          NTag,
          {
            type: row.isDefault ? 'success' : 'error',
          },
          {
            default: () => (row.isDefault ? '是' : '否'),
          }
        );
      },
    },
    {
      title: '操作',
      key: 'actions',
      align:'center',
      render (row) {
        return h("div", [
          h(
            NButton,
            {
              size: 'small',
              type:'success',
              style: {
                marginRight: "5px"
              },
              onClick: () => setPermission(row)
            },
            { default: () => '设置权限' }
          ),
          h(
            NButton,
            {
              type: "primary",
              size: "small",
              style: {
                marginRight: "5px"
              },
              onClick: () => handleEdit(row)
            },
            { default: () => '编辑' }
          ),
          h(
            NButton,
            {
              type: "error",
              size: "small",
              onClick: () => handleDelete(row)
            },
            { default: () => '删除' }
          )
        ]);
      }
    }
  ]);
  function setPermission(row){
    editRoleTitle.value = `分配 ${row.roleName} 的菜单权限`;
    roleId.value=row.id
    checkedKeys.value=row.menuIdList;
    showModal.value = true;
  }
  function initRoleData() {
    dataLoading.value=true;
    getRoleList(queryForm).then(res=>{
      roleData.value=res.records;
      pagination.value.itemCount=res.total
    })
    dataLoading.value=false;
  }
  function onSuccess() {
    initRoleData();
  }
  function handleCheck(keys) {
     selectRows.value=keys;
  }
  function expandedKeysTree(keys) {
    expandedKeys.value=keys
  }
  function clearSelect() {
    selectRows.value=[];
  }
  function add() {
    roleFormRef.value.isShow=true;
    drawerTitle.value='添加角色'
  }
  function handleSearch() {
    initRoleData();
  }
  function handleReSet() {
    queryForm.roleName='';
    initRoleData();
  }
  function changePageSize(value) {
    queryForm.pageSize = value
    pagination.value.pageSize=value;
    pagination.value.page=1;
    queryForm.page = 1
    initRoleData()
  }
  function confirmForm() {
    if(checkedKeys.value<=0){
      message.warning('请选择要设置的权限');
      return;
    }
    let formData={roleId:roleId.value,permissionIds:checkedKeys.value}
    formBtnLoading.value = true;
    saveRolePermission(formData).then(res=>{
      if(res){
        formBtnLoading.value = false;
        message.success("设置成功");
        showModal.value = false;
      }else{
        message.error(res.message);
      }
    })
  }

  function handleEdit(record: Recordable) {
    roleFormRef.value.isShow=true;
    record.dsType=record.dsType+''
    roleFormRef.value.form=record;
    roleFormRef.value.selectedDeptkeys=record.roleDeptIdList;
    drawerTitle.value='编辑角色【'+record.roleName+'】'
  }

  function handleDelete(record) {
    selectRows.value.push(record.id);
    batchDelete();
  }
  function batchDelete() {
    if(selectRows.value<=0){
       message.warning('请选择您要删除的数据')
      return;
    }
    dialog.warning({
      title: '警告',
      content: '你确定要删除所选数据？删除后无法回复',
      positiveText: '确定',
      negativeText: '取消',
      onPositiveClick: () => {
        let ids=selectRows.value.join(",");
        deleteRole(ids).then(res=>{
          if(res){
            message.success("删除成功");
            initRoleData();
          }else{
            message.error(res.message)
          }
        })
      },
      onNegativeClick: () => {
        selectRows.value=[]
      }
    })
  }
  function checkedTree(keys) {
    console.log(keys)
    checkedKeys.value = keys;
  }

  function packHandle() {
    if (expandedKeys.value.length) {
      expandedKeys.value = [];
    } else {
      expandedKeys.value = getTreeAll(treeData.value) as [];
    }
  }
  function checkedAllHandle() {
    if (!checkedAll.value) {
      checkedKeys.value = getTreeAll(treeData.value);
      checkedAll.value = true;
    } else {
      checkedKeys.value = [];
      checkedAll.value = false;
    }
  }

  onMounted(async () => {
    initRoleData()
    const treeMenuList = await getMenuList(null);
    expandedKeys.value = treeMenuList.map((item) => item.key);
    treeData.value = treeMenuList;
  });
</script>

<style lang="less" scoped>
  .operation {
    margin-bottom: 5px;
  }
  .flex-warp{
    flex-wrap: wrap;
  }
</style>
